package thread.synchroCode;

// 模式之保护性暂停，用在一个线程等待另一个线程的执行结果

import java.time.LocalDateTime;

public class _02GuardedSuspension {
  public static void main(String[] args) {
    String str = " Hellop HABI";
    Guarded guarded = new Guarded();

    new Thread(() -> {
      System.out.println("想要得到结果");
      synchronized (guarded){
        System.out.println("结果是" + guarded.getResponse(2000));
      }
      System.out.println("得到结果了");
    }).start();

    try {
      Thread.sleep(3000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    new Thread(() -> {
      System.out.println("我放数据来了");
      synchronized (guarded){
        guarded.setResponse(str);
      }
    }).start();
  }

  public static class Guarded{
    private String response;

    public String getResponse(long time){
      synchronized (this){
        // 获取开始时间
        long currTime = System.currentTimeMillis();
        // 保存已经等待了的时间
        long passedTime = 0;

        while (response == null){
          // 看经过的时间-开始开始是否超过了指定时间
          long waitTime = time - passedTime;
          if (waitTime <= 0){
            break;
          }
          try {
            System.out.println("还没数据，我歇逼了");
            this.wait(waitTime);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          passedTime = System.currentTimeMillis() - currTime;
        }
        return this.response;
      }
    }

    public void setResponse(String string){
      response = string;
      synchronized (this){
        this.notifyAll();
        System.out.println("我把数据放进去了");
      }
    }
  }
}
